<template>
	<div class="app-container">
    <el-form :inline="true" :model="dataForm" @submit.native.prevent @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input placeholder="请验编号" v-model="dataForm.queryCheckId" :clearable="true" type="number" size="mini">
          <template slot="prepend">请验编号</template>
        </el-input>
      </el-form-item>
      <br />
      <el-form-item>
        <el-input placeholder="品名" v-model="dataForm.productName" :clearable="true" size="mini">
          <template slot="prepend">品名</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="GMP编码" v-model="dataForm.productGmp" :clearable="true" size="mini">
          <template slot="prepend">GMP编码</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="批号" v-model="dataForm.batchNum" :clearable="true" size="mini">
          <template slot="prepend">批号</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          @change="setRegistCheckDate"
          v-model="dataForm.registCheckDate"
          type="daterange"
          range-separator="~"
          start-placeholder="请验时间起"
          end-placeholder="请验时间止"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          size="mini"/>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          @change="setReportDate"
          v-model="dataForm.reportDate"
          type="daterange"
          range-separator="~"
          start-placeholder="报告时间起"
          end-placeholder="报告时间止"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          size="mini"/>
      </el-form-item>

      <el-form-item>
        <el-select v-model="dataForm.status" clearable placeholder="全部状态" size="mini">
          <el-option label="待取样" value="1" />
          <el-option label="待收样" value="2" />
          <el-option label="待分样" value="3" />
          <el-option label="检验中" value="4,5" />
          <el-option label="待结论" value="6" />
          <el-option label="已结论" value="7,10,8,11" />
      	</el-select>
      </el-form-item>

      <el-form-item v-if="userInfo.types.length != 0">
        <el-select v-model="dataForm.checkTypeId" clearable placeholder="全部分类" size="mini">
          <el-option
            v-for="t in userInfo.types"
            :key="t.checkTypeId"
            :label="t.checkTypeName"
            :value="t.checkTypeId">
          </el-option>
      	</el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="pan-btn primary-btn" @click="searchData()" icon="el-icon-search" size="mini">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="dataForm.showBinding">搜索绑定的中间产品</el-checkbox>
      </el-form-item>
    </el-form>

    <el-table
    	:data="dataList"
    	v-loading="dataListLoading"
      ref="dataTable"
    	border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column
        prop="checkId"
        header-align="center"
        align="center"
        label="编号"
        width="80">
      </el-table-column>
      <el-table-column
      	prop="status"
      	header-align="center"
      	align="center"
      	label="状态"
        width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status == 6 ? 'danger' : row.status < 6 ? 'waring' : 'success'" size="small">
            {{ row.status | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="checkTypeName"
        header-align="center"
        align="center"
        label="分类"
        width="100">
      </el-table-column>
      <el-table-column
        prop="checkNum"
        header-align="center"
        align="center"
        label="报告编号">
      </el-table-column>
      <el-table-column
        prop="productName"
        header-align="center"
        align="center"
        label="品名">
      </el-table-column>
      <el-table-column
        prop="productGmp"
        header-align="center"
        align="center"
        label="GMP编码">
      </el-table-column>
      <el-table-column
        prop="batchNumPrefix"
        header-align="center"
        align="center"
        label="物料编码">
      </el-table-column>
      <el-table-column
        prop="productSpec"
        header-align="center"
        align="center"
        label="货品规格">
        <template slot-scope="{row}">
          <span v-html="row.productSpec"></span>
        </template>
      </el-table-column>
      <el-table-column
        prop="registCheckUserName"
        header-align="center"
        align="center"
        label="请验人">
      </el-table-column>
      <el-table-column
        prop="registCheckDate"
        header-align="center"
        align="center"
        label="请验时间">
        <template slot-scope="{row}">{{row.registCheckDate | changeTime}}</template>
      </el-table-column>
      <el-table-column
        prop="inspectDate"
        header-align="center"
        align="center"
        label="检验时间">
        <template slot-scope="{row}">{{row.inspectDate | changeTime}}</template>
      </el-table-column>
      <el-table-column
        prop="allProcedureNames"
        header-align="center"
        align="center"
        label="所有工序">
        <template slot-scope="{row}">
          <span style="color: #67C23A;">{{ row.finishProcedureNames | procedureNameFilter }}</span>
          <span style="color: #F56C6C;">{{ row.waitProcedureNames | procedureNameFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="dataForm.checkTypeId == 6"
        prop="stabilityModeName"
        header-align="center"
        align="center"
        label="考察方式">
        <template slot-scope="{row}">
          {{ row.stabilityModeName + ' ' + row.timeValue + row.timeName }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="dataForm.showBinding"
        prop="binds"
        header-align="center"
        align="center"
        label="中间品">
        <template slot-scope="{row}">
          <template v-if="row.bindingZp == 0">
            <template v-if="row.binds == null">
              <span style="color: red">未发起</span>
            </template>
            <template v-else>
              <span v-for="cl in row.binds" :key="cl.checkId">
                <el-button plain size="mini" @click="show(cl.checkTypeId,cl.productGmp,cl.batchNum)">{{ cl.productGmp }}</el-button>
              </span>
            </template>
          </template>
          <template v-else>
            未绑定
          </template>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <template v-if="scope.row.status == 6 && isAuth('check:verdict')">
            <el-button type="danger" class="pan-btn danger-btn" size="mini" @click="verdict(scope.row)">结论</el-button>
          </template>
          <template v-if="scope.row.status == 4 || scope.row.status == 5">
            <el-button type="warning" class="pan-btn warning-btn" size="mini" @click="show(scope.row.checkTypeId,scope.row.productGmp,scope.row.batchNumPrefix)">进度</el-button>
          </template>
          <template v-if="scope.row.status == 4 || scope.row.status == 5 && isAuth('check:verdict')">
            <br><el-button type="warning" class="pan-btn warning-btn" size="mini" @click="flush(scope.row.checkMergeId)">刷新</el-button>
          </template>
          <template v-if="scope.row.status > 6">
            <el-col>
              <el-button type="success" class="pan-btn success-btn" size="mini"  @click="print(scope.row,'报告书')">打印报告书</el-button>
            </el-col>
<!--            <template v-if="scope.row.checkTypeId == 5 && parseInt(scope.row.batchNumPrefix.replace(/[^0-9]+/g,'').substring(0,2)) > 20">
              <el-col>
                <el-button type="info" class="pan-btn info-btn" size="mini"  @click="printPass(scope.row)">打印放行单</el-button>
              </el-col>
            </template> -->
          </template>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="详情"
        width="100">
        <template slot-scope="scope">
          <el-button type="info" class="pan-btn info-btn" size="mini" @click="info(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <check-info
      v-if="infoVisible"
      @close="close('infoVisible')"
      @refreshData="getDataList"
      :childDataForm="childDataForm" />

    <check-info-merge
      v-if="infoMergeVisible"
      @close="close('infoMergeVisible')"
      @refreshData="getDataList"
      :childDataForm="childDataForm" />

    <verdict
      v-if="verdictVisible"
      @close="close('verdictVisible')"
      @print="print"
      @refreshData="getDataList"
      :childDataForm="childDataForm" />

    <print
      v-if="printVisible"
      @close="close('printVisible')"
      :childDataForm="childDataForm" />

    <el-dialog
      title="选择要打印的放行审核单"
      :visible.sync="selectPrintPassVisible"
      @before-close="close('selectPrintPassVisible')"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="30%">
      <div>
        <el-button type="info" class="pan-btn info-btn" size="mini" @click="updateCheckListsPrintPassNumberForCurrent('成品上市放行审核单（自行生产）')">成品上市放行审核单（01版自行生产）</el-button>
        <el-button type="info" class="pan-btn info-btn" size="mini" @click="updateCheckListsPrintPassNumberForCurrent('成品出厂放行审核单（受托生产）')">成品出厂放行审核单（01版受托生产）</el-button>
        <el-button type="info" class="pan-btn info-btn" size="mini" @click="updateCheckListsPrintPassNumberForCurrent('成品上市放行审核单（2自行生产）')">成品上市放行审核单（02版自行生产）</el-button>
        <el-button type="info" class="pan-btn info-btn" size="mini" @click="updateCheckListsPrintPassNumberForCurrent('成品出厂放行审核单（2受托生产）')">成品出厂放行审核单（02版受托生产）</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close('selectPrintPassVisible')">取 消</el-button>
      </span>
    </el-dialog>

	</div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import CommonMethod from '@/views/mixin/common'
  import { CODE_OK } from '@/common/js/config'
  import {
    checkList,
    printParasiteInit,
    flushCheckStatus,
    finishMergeList,
    updateCheckListsPrintPassNumberForCurrent
  } from '@/api/check'
  import { isBlank } from '@/common/js/utils'
  import CheckInfo from '@/views/modules/process/common/check-info'
  import CheckInfoMerge from '@/views/modules/process/common/check-info-merge'
  import Verdict from '@/views/modules/process/verdict/verdict'
  // import Print from '@/views/modules/print'
  import Print from '@/views/modules/printmodel/printchoice'
	export default {
    name: 'jielun',
    filters: {
      procedureNameFilter(name) {
        if (!isBlank(name)) {
          return name.replace(',',' ')
        }
        return null
      },
      statusFilter(status) {
        const statusMap = {
          0: '待处理',
          1: '待取样',
          2: '待收样',
          3: '待分发',
          4: '检验中',
          5: '检验中',
          6: '待结论',
          10: '待放行',
          7: '待放行',
          8: '待确认',
          11: '已完成',
          9: '已作废'
        }
        return statusMap[status]
      }
    },
    mixins: [CommonMethod],
    components: {
    	CheckInfo,CheckInfoMerge,Verdict,Print
    },
		data(){
      return{
        printClassify: '报告书',
        currentStatus: 6,
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataForm: {
          status: '6',
          showBinding: false
        },
        childDataForm: '',
        infoVisible: false,
        infoMergeVisible: false,
        verdictVisible: false,
        printVisible: false,
        waitRow: {},
        selectPrintPassVisible: false,
        next: ''
      }
		},
    mounted() {
    	this.getInfo()
    },
    computed: {
      ...mapGetters([
         'userInfo'
      ])
    },
		methods:{
      printPass(row) {
        if (row) {
          this.waitRow = row
        }
        if (isBlank(this.waitRow.printPassNumber)) {
          this.selectPrintPassVisible = true
        }else{
          // this.showPrintPass()
          this.selectPrintPassVisible = true
        }
      },
      updateCheckListsPrintPassNumberForCurrent(printClassify) {
        const data = {
          checkMergeId: this.waitRow.checkMergeId,
          printClassify: printClassify
        }
        updateCheckListsPrintPassNumberForCurrent(data).then(res => {
          if (res.code === CODE_OK) {
            this.waitRow.printPassNumber = res.printPassNumber
            this.showPrintPass()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      showPrintPass() {
        this.next = null
        this.childDataForm = JSON.parse(JSON.stringify(this.waitRow))
        this.$set(this.childDataForm, 'printNumber', this.childDataForm.printPassNumber)
        this.printVisible = true
      },
      flush(checkMergeId) {
        const data = {
          checkMergeId: checkMergeId
        }
        flushCheckStatus(data).then(res => {
          if (res.code === CODE_OK) {
          	this.getDataList()
          }else if(res.code === 996){
            this.$confirm(res.msg, {
              confirmButtonText: '是',
              cancelButtonText: '否'
            }).then(async () => {
              finishMergeList(data).then(res => {
                if (res.code === CODE_OK) {
                	this.getDataList()
                }else{
                  this.$message.error(res.msg)
                }
              })
            }).catch(() => {})
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      print(row,tag) {
        // 同一批第二次及以后的留样外包单，没有打印版本说明没有初始化
        if (row.isParasite == 0 && row.printReportVersion == null) {
          printParasiteInit(row).then(res => {
            if (res.code === CODE_OK) {
            	this.showReport(res.list)
            }else{
            	this.$message.error(res.msg)
            }
          })
        }else{
          this.showReport(row,tag)
        }
      },
      showReport(row,tag) {
        this.childDataForm = JSON.parse(JSON.stringify(row))
        this.$set(this.childDataForm, 'printClassify', this.printClassify)
        this.$set(this.childDataForm, 'printType', tag)
        this.$set(this.childDataForm, 'unfinish', false)
        if (row.isHalf == 0) {
          this.$confirm('', {
            confirmButtonText: '总结论后报告',
            cancelButtonText: '第一次报告',
            center: true
          }).then(() => {
            this.printVisible = true
          }).catch(() => {
            this.childDataForm.unfinish = true
            this.childDataForm.reportDate = JSON.parse(JSON.stringify(this.childDataForm.halfReportDate))
            this.printVisible = true
          })
        }else{
          this.printVisible = true
        }
      },
      searchData() {
      	this.pageIndex=1
      	this.getDataList()
      },
      getInfo() {
        this.getDataList()
      },
      getDataList() {
      	this.dataListLoading = true
        const params = {
          page: this.pageIndex,
          limit: this.pageSize,
          status: this.dataForm.status || '1,2,3,4,5,6,10,7,8,11',
          isMerge: 0,
          checkTypeId: this.dataForm.checkTypeId || this.userInfo.types.map(t => {return t.checkTypeId}).join(','),
          productName: this.dataForm.productName || null,
          productGmp: this.dataForm.productGmp || null,
          batchNum: this.dataForm.batchNum || null,
          startTime: this.dataForm.startTime || null,
          endTime: this.dataForm.endTime || null,
          reportDateStart: this.dataForm.reportDateStart || null,
          reportDateEnd: this.dataForm.reportDateEnd || null,
          showBinding: this.dataForm.showBinding || null,
          checkId: this.dataForm.queryCheckId || null
        }
        checkList(params).then(res => {
        	if (res.code === CODE_OK) {
        		this.dataList = res.page.list
        		this.totalPage = res.page.totalCount
        	}else{
        		this.$message.error(res.msg)
        	}
        	this.dataListLoading = false
        }).catch()
      },
      info(row) {
        this.childDataForm = {
          currentStatus: this.currentStatus,
          info: row
        }
        if (row.isMerge == 0) {
          this.infoMergeVisible = !this.infoMergeVisible
        }else{
          this.infoVisible = !this.infoVisible
        }
      },
      verdict(row) {
         this.childDataForm = JSON.parse(JSON.stringify(row))
        if (row.checkTypeId == 5) {
          this.next = 'showReportAndPass'
          this.waitRow = JSON.parse(JSON.stringify(row))
        }else{
          this.next = null
          this.waitRow = null
        }
        this.verdictVisible = !this.verdictVisible
      },
      show(checkTypeId, productGmp, batchNumPrefix) {
        this.$router.push({
          name: '检验进度查询',
          params: {
            serachInfo: {
              checkTypeId: checkTypeId,
              productGmp: productGmp,
              batchNum: batchNumPrefix
            }
          }
        })
      },
      close(val) {
        this.childDataForm = ''
        this[val] = false
        if (val == 'printVisible') {
          this.selectPrintPassVisible = (this.next == 'showReportAndPass' && !isBlank(this.waitRow))
        }
      },
      setRegistCheckDate() {
        if (!isBlank(this.dataForm.registCheckDate)) {
          this.dataForm.startTime = this.dataForm.registCheckDate[0]
          this.dataForm.endTime = this.dataForm.registCheckDate[1]
        }else{
          this.dataForm.startTime = null
          this.dataForm.endTime = null
        }
      },
      setReportDate() {
        if (!isBlank(this.dataForm.reportDate)) {
          this.dataForm.reportDateStart = this.dataForm.reportDate[0]
          this.dataForm.reportDateEnd = this.dataForm.reportDate[1]
        }else{
          this.dataForm.reportDateStart = null
          this.dataForm.reportDateEnd = null
        }
      }
		}
	}
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: normal;
  }
</style>
